Hands-on Exercise 03

Author

Marga Thura

Published

April 26, 2025

Modified

May 2, 2025

3 Programming Interactive Data Visualisation with R

3.1 Getting Started

First, a code chunk to check, install and launch the following R packages:

  • ggiraph for making ‘ggplot’ graphics interactive.
  • plotly, R library for plotting interactive statistical graphs.
  • DT provides an R interface to the JavaScript library DataTables that create interactive table on html page.
  • tidyverse, a family of modern R packages specially designed to support data science, analysis and communication task including creating static statistical graphs.
  • patchwork for combining multiple ggplot2 graphs into one figure.
  • The code chunk below will be used to accomplish the task.
pacman::p_load(ggiraph, plotly, 
               patchwork, DT, tidyverse) 

3.2 Importing Data

In this section, Exam_data.csv provided will be used. Using read_csv() of readr package, import Exam_data.csv into R. The code chunk below read_csv() of readr package is used to import Exam_data.csv data file into R and save it as an tibble data frame called exam_data.

exam_data <- read_csv("Data_03/Exam_data.csv")

3.3 Interactive Data Visualisation - ggiraph methods

ggiraph is an htmlwidget and a ggplot2 extension. It allows ggplot graphics to be interactive.

Interactive is made with ggplot geometries that can understand three arguments:

Tooltip: a column of data-sets that contain tooltips to be displayed when the mouse is over elements. Onclick: a column of data-sets that contain a JavaScript function to be executed when elements are clicked. Data_id: a column of data-sets that contain an id to be associated with elements.

If it used within a shiny application, elements associated with an id (data_id) can be selected and manipulated on client and server sides.

3.3.1 Configuring selections

The graphics produced by girafe() from a shiny application allows you to retrieve the element selections made by users.

Elements associated with data_id can be selected and the selection (the data_id value) is available in the client and the server side of the application. The selected identifiers will be the values mapped by the aesthetic data_id.

3.3.2 Type of selection

The selection type can take several values: single, multiple or none.

  • single : the user can only select one element. The click allows its selection if it is not selected, or its de-selection if it is already selected. Clicking on an unselected element automatically de-selects the other selected element.

  • multiple: the user can select several elements. He can do this by clicking on the elements or by selecting in the toolbar the “lasso selection” menu which allows you to draw a lasso on the graph and select all the elements contained in the lasso. The toolbar also contains an “anti-lasso selection” menu that allows you to draw a lasso on the graph and de-select all the elements contained in the lasso. The click is of course available for unit selections/de-selections.

  • none: no selection is allowed in the graph produced by girafe.

All these options can be configured with the following functions:

  • opts_selection(): relative to panel selections
  • opts_selection_key(): relative to legend selections
  • opts_selection_theme(): relative to theme elements selections
library(tidyverse)
mtcars_db <- rownames_to_column(mtcars, var = "carname")

gg_scatter <- ggplot(
  data = mtcars_db, 
  mapping = aes(
    x = disp, y = qsec, tooltip = carname, 
    data_id = carname, color= wt)) +
    geom_point_interactive(size=3)

girafe(ggobj = gg_scatter, 
  options = list(
    opts_selection(
      type = "single", 
      only_shiny = FALSE))
)
preselection <- mtcars_db$carname[1:5]
girafe(ggobj = gg_scatter, 
  options = list(
    opts_selection(
      selected = preselection, 
      type = "multiple", 
      only_shiny = FALSE
    )
  )
)
preselection <- mtcars_db$carname[1:5]
girafe(ggobj = gg_scatter, 
  options = list(
    opts_selection(
      selected = preselection, 
      type = "multiple", 
      only_shiny = FALSE
    )
  )
)

3.4 Methods to display

p <- ggplot(data=exam_data, 
       aes(x = MATHS)) +
  geom_dotplot_interactive(           
    aes(data_id = CLASS),             
    stackgroups = TRUE,               
    binwidth = 1,                        
    method = "histodot") +               
  scale_y_continuous(NULL,               
                     breaks = NULL)
girafe(                                  
  ggobj = p,                             
  width_svg = 6,                         
  height_svg = 6*0.618                      
)                                        
p <- ggplot(data=exam_data, 
       aes(x = MATHS)) +
  geom_dotplot_interactive(
    aes(tooltip = ID),
    stackgroups = TRUE, 
    binwidth = 1, 
    method = "histodot") +
  scale_y_continuous(NULL, 
                     breaks = NULL)
girafe(
  ggobj = p,
  width_svg = 6,
  height_svg = 6*0.618
)
exam_data$tooltip <- c(paste0(     
  "Name = ", exam_data$ID,         
  "\n Class = ", exam_data$CLASS)) 

p <- ggplot(data=exam_data, 
       aes(x = MATHS)) +
  geom_dotplot_interactive(
    aes(tooltip = exam_data$tooltip), 
    stackgroups = TRUE,
    binwidth = 1,
    method = "histodot") +
  scale_y_continuous(NULL,               
                     breaks = NULL)
girafe(
  ggobj = p,
  width_svg = 8,
  height_svg = 8*0.618
)
tooltip_css <- "background-color:yellow; #<<
font-style:bold; color:black;" #<<

p <- ggplot(data=exam_data, 
       aes(x = MATHS)) +
  geom_dotplot_interactive(              
    aes(tooltip = ID),                   
    stackgroups = TRUE,                  
    binwidth = 1,                        
    method = "histodot") +               
  scale_y_continuous(NULL,               
                     breaks = NULL)
girafe(                                  
  ggobj = p,                             
  width_svg = 6,                         
  height_svg = 6*0.618,
  options = list(    #<<
    opts_tooltip(    #<<
      css = tooltip_css)) #<<
)

3.4.1 Hover effects and customizing girafe animations

Another option can be used to alter aspect of non hovered elements. It is very useful to highlight hovered elements when the density of the elements is high by fixing less opacity on the other elements.

dat <- read.csv("C:/Users/marga/mgtr/ISS608-VAA/Hands-on_Ex/Hands-on_Ex03/Data_03/Exam_data.csv")

gg <- ggplot(dat, aes(x = ENGLISH, y = MATHS, 
                      colour = RACE, group = GENDER)) +
  geom_line_interactive(aes(tooltip = ID, data_id = ID)) +
  scale_color_viridis_d() + 
  labs(title = "move mouse over lines")

x <- girafe(ggobj = gg, width_svg = 8, height_svg = 6,
  options = list(
    opts_hover_inv(css = "opacity:0.1;"),
    opts_hover(css = "stroke-width:2;")
  ))

x
p <- ggplot(data=exam_data, 
       aes(x = MATHS)) +
  geom_dotplot_interactive(              
    aes(data_id = CLASS),              
    stackgroups = TRUE,                  
    binwidth = 1,                        
    method = "histodot") +               
  scale_y_continuous(NULL,               
                     breaks = NULL)
girafe(                                  
  ggobj = p,                             
  width_svg = 6,                         
  height_svg = 6*0.618,
  options = list(                        
    opts_hover(css = "fill: #202020;"),  
    opts_hover_inv(css = "opacity:0.2;") 
  )                                        
)     
p <- ggplot(data=exam_data, 
       aes(x = MATHS)) +
  geom_dotplot_interactive(              
    aes(tooltip = CLASS, 
        data_id = CLASS),              
    stackgroups = TRUE,                  
    binwidth = 1,                        
    method = "histodot") +               
  scale_y_continuous(NULL,               
                     breaks = NULL)
girafe(                                  
  ggobj = p,                             
  width_svg = 6,                         
  height_svg = 6*0.618,
  options = list(                        
    opts_hover(css = "fill: #202020;"),  
    opts_hover_inv(css = "opacity:0.2;") 
  )                                        
)                                        
exam_data$onclick <- sprintf("window.open(\"%s%s\")",
"https://www.moe.gov.sg/schoolfinder?journey=Primary%20school",
as.character(exam_data$ID))

p <- ggplot(data=exam_data, 
       aes(x = MATHS)) +
  geom_dotplot_interactive(              
    aes(onclick = onclick),              
    stackgroups = TRUE,                  
    binwidth = 1,                        
    method = "histodot") +               
  scale_y_continuous(NULL,               
                     breaks = NULL)
girafe(                                  
  ggobj = p,                             
  width_svg = 6,                         
  height_svg = 6*0.618)                                        
p1 <- ggplot(data=exam_data, 
       aes(x = MATHS)) +
  geom_dotplot_interactive(              
    aes(data_id = ID),              
    stackgroups = TRUE,                  
    binwidth = 1,                        
    method = "histodot") +  
  coord_cartesian(xlim=c(0,100)) + 
  scale_y_continuous(NULL,               
                     breaks = NULL)

p2 <- ggplot(data=exam_data, 
       aes(x = ENGLISH)) +
  geom_dotplot_interactive(              
    aes(data_id = ID),              
    stackgroups = TRUE,                  
    binwidth = 1,                        
    method = "histodot") + 
  coord_cartesian(xlim=c(0,100)) + 
  scale_y_continuous(NULL,               
                     breaks = NULL)

girafe(code = print(p1 + p2), 
       width_svg = 6,
       height_svg = 3,
       options = list(
         opts_hover(css = "fill: #202020;"),
         opts_hover_inv(css = "opacity:0.2;")
         )
       ) 

3.4.2 Displaying statistics on tooltip

tooltip <- function(y, ymax, accuracy = .01) {
  mean <- scales::number(y, accuracy = accuracy)
  sem <- scales::number(ymax - y, accuracy = accuracy)
  paste("Mean maths scores:", mean, "+/-", sem)
}

gg_point <- ggplot(data=exam_data, 
                   aes(x = RACE),
) +
  stat_summary(aes(y = MATHS, 
                   tooltip = after_stat(  
                     tooltip(y, ymax))),  
    fun.data = "mean_se", 
    geom = GeomInteractiveCol,  
    fill = "light blue"
  ) +
  stat_summary(aes(y = MATHS),
    fun.data = mean_se,
    geom = "errorbar", width = 0.2, size = 0.2
  )

girafe(ggobj = gg_point,
       width_svg = 8,
       height_svg = 8*0.618)

3.5 Interactive Data Visualisation - plotly methods!

Plotly’s R graphing library create interactive web graphics from ggplot2 graphs and/or a custom interface to the (MIT-licensed) JavaScript library plotly.js inspired by the grammar of graphics. Different from other plotly platform, plot.R is free and open source.

plot_ly(data = exam_data, 
             x = ~MATHS, 
             y = ~ENGLISH)
plot_ly(data = exam_data, 
        x = ~ENGLISH, 
        y = ~MATHS, 
        color = ~RACE)
p <- ggplot(data=exam_data, 
            aes(x = MATHS,
                y = ENGLISH)) +
  geom_point(size=1) +
  coord_cartesian(xlim=c(0,100),
                  ylim=c(0,100))
ggplotly(p)
d <- highlight_key(exam_data)
p1 <- ggplot(data=d, 
            aes(x = MATHS,
                y = ENGLISH)) +
  geom_point(size=1) +
  coord_cartesian(xlim=c(0,100),
                  ylim=c(0,100))

p2 <- ggplot(data=d, 
            aes(x = MATHS,
                y = SCIENCE)) +
  geom_point(size=1) +
  coord_cartesian(xlim=c(0,100),
                  ylim=c(0,100))
subplot(ggplotly(p1),
        ggplotly(p2))

3.6 Interactive Data Visualisation - crosstalk methods!

Crosstalk is an add-on to the htmlwidgets package. It extends htmlwidgets with a set of classes, functions, and conventions for implementing cross-widget interactions (currently, linked brushing and filtering).

3.6.1 Interactive Data Table: DT package

  • A wrapper of the JavaScript Library DataTables

  • Data objects in R can be rendered as HTML tables using the JavaScript library ‘DataTables’ (typically via R Markdown or Shiny).

DT::datatable(exam_data, class= "compact")

3.6.2 Linked brushing: crosstalk method

Things to learn from the code:

highlight() is a function of plotly package. It sets a variety of options for brushing (i.e., highlighting) multiple plots. These options are primarily designed for linking multiple plotly graphs, and may not behave as expected when linking plotly to another htmlwidget package via crosstalk. In some cases, other htmlwidgets will respect these options, such as persistent selection in leaflet.

bscols() is a helper function of crosstalk package. It makes it easy to put HTML elements side by side. It can be called directly from the console but is especially designed to work in an R Markdown document. Warning: This will bring in all of Bootstrap!.

d <- highlight_key(exam_data) 
p <- ggplot(d, 
            aes(ENGLISH, 
                MATHS)) + 
  geom_point(size=1) +
  coord_cartesian(xlim=c(0,100),
                  ylim=c(0,100))

gg <- highlight(ggplotly(p),        
                "plotly_selected")  

crosstalk::bscols(gg,               
                  DT::datatable(d), 
                  widths = 5) 

3.7 Reference

3.7.1 ggiraph

This link provides online version of the reference guide and several useful articles. Use this link to download the pdf version of the reference guide.

3.7.2 plotly for R

4 Programming Animated Statistical Graphics with R

4.1 Overview

When telling a visually-driven data story, animated graphics tends to attract the interest of the audience and make deeper impression than static graphics. In this hands-on exercise, we will learn how to create animated data visualisation by using gganimate and plotly r packages. At the same time, we will also learn how to (i) reshape data by using tidyr package, and (ii) process, wrangle and transform data by using dplyr package.

4.1.1 Basic concepts of animation

When creating animations, the plot does not actually move. Instead, many individual plots are built and then stitched together as movie frames, just like an old-school flip book or cartoon. Each frame is a different plot when conveying motion, which is built using some relevant subset of the aggregate data. The subset drives the flow of the animation when stitched back together.

4.1.2 Terminology

Before we dive into the steps for creating an animated statistical graph, it’s important to understand some of the key concepts and terminology related to this type of visualization.

  1. Frame: In an animated line graph, each frame represents a different point in time or a different category. When the frame changes, the data points on the graph are updated to reflect the new data.

  2. Animation Attributes: The animation attributes are the settings that control how the animation behaves. For example, you can specify the duration of each frame, the easing function used to transition between frames, and whether to start the animation from the current frame or from the beginning.

Tip

Before you start making animated graphs, you should first ask yourself: Does it makes sense to go through the effort? If you are conducting an exploratory data analysis, a animated graphic may not be worth the time investment. However, if you are giving a presentation, a few well-placed animated graphics can help an audience connect with your topic remarkably better than static counterparts.

4.2 Getting Started

4.2.1 Loading the R packages

First, a code chunk to check, install and load the following R packages:

  • plotly, R library for plotting interactive statistical graphs.

  • gganimate, an ggplot extension for creating animated statistical graphs.

  • gifski converts video frames to GIF animations using pngquant’s fancy features for efficient cross-frame palettes and temporal dithering. It produces animated GIFs that use thousands of colors per frame.

  • gapminder: An excerpt of the data available at Gapminder.org. We just want to use its country_colors scheme.

  • tidyverse, a family of modern R packages specially designed to support data science, analysis and communication task including creating static statistical graphs.

pacman::p_load(readxl, gifski, gapminder,
               plotly, gganimate, tidyverse)

4.2.2 Importing the data

In this hands-on exercise, the Data worksheet from GlobalPopulation Excel workbook will be used.

Write a code chunk to import Data worksheet from GlobalPopulation Excel workbook by using appropriate R package from tidyverse family:

col <- c("Country", "Continent")
globalPop <- read_xls("C:/Users/marga/mgtr/ISS608-VAA/Hands-on_Ex/Hands-on_Ex03/Data_03/GlobalPopulation.xls",
                      sheet="Data") %>%
  mutate(across(col, as.factor)) %>%
  mutate(Year = as.integer(Year))
Things to learn from the code chunk above
  • read_xls() of readxl package is used to import the Excel worksheet.
  • across() makes it easy to apply the same transformation to multiple columns, allowing you to use select() semantics inside in “data-masking” functions like summarise() and mutate().
  • mutate of dplyr package is used to convert data values of Year field into integer.

4.3 Animated Data Visualisation: gganimate methods

gganimate extends the grammar of graphics as implemented by ggplot2 to include the description of animation. It does this by providing a range of new grammar classes that can be added to the plot object in order to customise how it should change with time.

  • transition_*() defines how the data should be spread out and how it relates to itself across time.

  • view_*() defines how the positional scales should change along the animation.

  • shadow_*() defines how data from other points in time should be presented in the given point in time.

  • enter_*()/exit_*() defines how new data should appear and how old data should disappear during the course of the animation.

  • ease_aes() defines how different aesthetics should be eased during transitions.

4.3.1 Building a static or animated bubble plot

In the code chunks below, the basic ggplot2 functions are used to create a static bubble plot as well as transition_time() of gganimate is used to create transition through distinct states in time (i.e. Year). ease_aes() is used to control easing of aesthetics. The default is linear. Other methods are: quadratic, cubic, quartic, quintic, sine, circular, exponential, elastic, back, and bounce.

ggplot(globalPop, aes(x = Old, y = Young, 
                      size = Population, 
                      colour = Country)) +
  geom_point(alpha = 0.7, 
             show.legend = FALSE) +
  scale_colour_manual(values = country_colors) +
  scale_size(range = c(2, 12)) +
  labs(title = 'Year: {frame_time}', 
       x = '% Aged', 
       y = '% Young') 

ggplot(globalPop, aes(x = Old, y = Young, 
                      size = Population, 
                      colour = Country)) +
  geom_point(alpha = 0.7, 
             show.legend = FALSE) +
  scale_colour_manual(values = country_colors) +
  scale_size(range = c(2, 12)) +
  labs(title = 'Year: {frame_time}', 
       x = '% Aged', 
       y = '% Young') +
  transition_time(Year) +       
  ease_aes('linear')  

4.4 Other animated plot methods

4.4.1 Line Animated Plot

p <- ggplot(globalPop, aes(x = Year, y = Young, group = Country, color = Country)) +
  geom_line() +
  labs(x = "Year", y = "% Young Population") +
  theme_minimal() +
  theme(legend.position = "none")

# Animated reveal
p + transition_reveal(Year)

4.4.2 Data Transition Plot

library(dplyr)

mean_young <- globalPop %>%
  group_by(Year) %>%
  summarise(MeanYoung = mean(Young, na.rm = TRUE))

p <- ggplot(mean_young, aes(x = Year, y = MeanYoung, fill = MeanYoung)) +
  geom_col() +
  scale_fill_distiller(palette = "Blues", direction = 1) +
  theme_minimal() +
  theme(
    panel.grid = element_blank(),
    panel.grid.major.y = element_line(color = "white"),
    panel.ontop = TRUE
  )

p + 
  transition_states(Year, wrap = FALSE) +
  shadow_mark() +
  enter_grow() +
  enter_fade()

4.4.3 Simple box plot

ggplot(globalPop, aes(x = Continent, y = Young)) + 
  geom_boxplot() + 
  transition_states(
    Year,
    transition_length = 2,
    state_length = 1
  ) +
  labs(title = "Year: {closest_state}",
       x = "Continent", 
       y = "% Young Population") +
  enter_fade() +
  exit_shrink() +
  ease_aes('sine-in-out') 

4.4.4 Plot using the gapminder

ggplot(globalPop, aes(x = Old, y = Young, 
                      size = Population, 
                      colour = Country)) +
  geom_point(alpha = 0.7, show.legend = FALSE) +
  # Remove this line or define country_colors as a named vector
  # scale_colour_manual(values = country_colors) +
  scale_size(range = c(2, 12)) +
  facet_wrap(~Continent) +
  labs(title = 'Year: {frame_time}', 
       x = '% Aged', 
       y = '% Young') +
  transition_time(Year) +
  ease_aes('linear')

4.5 Animated Data Visualisation: plotly

In Plotly R package, both ggplotly() and plot_ly() support key frame animations through the frame argument/aesthetic. They also support an ids argument/aesthetic to ensure smooth transitions between objects with the same id (which helps facilitate object constancy).

4.5.1 an animated bubble plot: ggplotly() method

gg <- ggplot(globalPop, 
       aes(x = Old, 
           y = Young, 
           size = Population, 
           colour = Country)) +
  geom_point(aes(size = Population,
                 frame = Year),
             alpha = 0.7, 
             show.legend = FALSE) +
  scale_colour_manual(values = country_colors) +
  scale_size(range = c(2, 12)) +
  labs(x = '% Aged', 
       y = '% Young')

ggplotly(gg)
gg <- ggplot(globalPop, 
       aes(x = Old, 
           y = Young, 
           size = Population, 
           colour = Country)) +
  geom_point(aes(size = Population,
                 frame = Year),
             alpha = 0.7) +
  scale_colour_manual(values = country_colors) +
  scale_size(range = c(2, 12)) +
  labs(x = '% Aged', 
       y = '% Young') + 
  theme(legend.position='none')

ggplotly(gg)

4.5.2 an animated bubble plot: plot_ly() method

bp <- globalPop %>%
  plot_ly(x = ~Old, 
          y = ~Young, 
          size = ~Population, 
          color = ~Continent,
          sizes = c(2, 100),
          frame = ~Year, 
          text = ~Country, 
          hoverinfo = "text",
          type = 'scatter',
          mode = 'markers'
          ) %>%
  layout(showlegend = FALSE)
bp

4.6 Reference